<?php
require_once 'Action.php';
require_once 'class/lib/utils.php';
/**
 * Take class, take objects from floor or containers
 * @package action
 * @author alcaitiff
 */
class Take implements Action{

    /**
     * @static
     * @var integer
     **/
	static private $tick;
    /**
     * @static
     * @var Char
     **/
	static private $char;
    /**
    * Usage: take [number|"all"] Item [number] [container [number]]
	*
	* If both hands are accupied the command will fail.
    * The container may be on hands or floor, if container parameter is not present the item must be on floor
	* @static
    * @param Command $command Command
    * @param int $tick Tick
    * @return String This command will return a msg
    */
	static public function run($command,$tick){
		self::$tick=$tick;
		self::$char=$command->character;
        $parameters=$command->getArrangedParameters(1,5,true);
		if($parameters==NULL){
            MessageSystem::addErrorMessage('Invalid Parameters');
            return null;
        }else{
            return self::takeItem($parameters[0], $parameters[1], $parameters[2], (isset($parameters[3]))?$parameters[3]:null, (isset($parameters[4]))?$parameters[4]:null);
        }
	}
    /**
     * Take an Item
     * @param int|string $num
     * @param string $name
     * @param int $index
     * @param string $containerName
     * @param int $containerIndex
     * @return string
     */
    static private function takeItem($num,$name,$index,$containerName=null,$containerIndex=1){
        $item=null;
        $container=null;
        if($index>1){
            $errorMessage=$name.'['.$index.'] not found';
        }else{
            $errorMessage=$name.' not found';
        }
        //Get from floor
        if($containerName===null){
            $room=self::$char->getRoom();
            $floor=$room->getItemsByName($name,$index);
            if(count($floor)>=$index){
                //found!
                $floor=array_slice($floor,$index-1,1,TRUE);
                $item = new Item(key($floor));
            }else{
                MessageSystem::addErrorMessage($errorMessage);
                return null;
            }
        }else{
            //get container
            $container=self::$char->getItem($containerName, $containerIndex);
            if($container!==NULL){
                if($container->container!=null){
                    //get item from container
                    $item=$container->container->getItemByName($name,$index);
                }
            }
        }
        if($item===null){
            return null;
        }
        
        return self::$char->takeItem($item,$num,$container);
    }
    
}